package com.jxy.homepage.web.api;

import com.jxy.BBM_info.BBM;
import com.jxy.BBM_info.BBM_table;
import com.jxy.homepage.config.annotation.ControllerWebLog;
import com.jxy.homepage.domain.User;
import com.jxy.homepage.service.UserService;
import com.jxy.homepage.service.feign.MailClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.validation.Valid;


/**
 * UserController
 *
 * @author Jxy
 * @date 2022/1/6
 * @Description token获取 用户登录
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
public class UserController {

    private final UserService userService;
    private final RestTemplate restTemplate;
    private final MailClient mailClient;

    public UserController(UserService userService, RestTemplate restTemplate, MailClient mailClient) {
        this.userService = userService;
        this.restTemplate = restTemplate;
        this.mailClient = mailClient;
    }

    @ControllerWebLog(name = "登录")
    @PostMapping(value = "/login")
    public ResponseEntity<String> login(@RequestBody @Valid User user, BindingResult bindingResult) {
        // 如果有参数校验失败，会将错误信息封装成对象组装在BindingResult里
        for (ObjectError error : bindingResult.getAllErrors()) {
            return ResponseEntity.badRequest().body(error.getDefaultMessage());
        }

        String token = userService.createToken(user);

        BBM bbm = new BBM();
        BBM_table mail = new BBM_table();
        mail.addColumns(new String[]{"TO", "SUBJECT", "CONTENT"});
        mail.addRow(new Object[]{"jseryx@126.com", "测试微服务调用template", "测试内容"});
        bbm.addTable(mail);

        // 登录成功 发送邮件通知管理员等等操作 微服务调用方式一
        // restTemplate.postForObject("http://mail/api/sendMail", bbm, BBM.class);
        // 微服务调用方式二 OpenFeign
        try {
            mailClient.sendMail(bbm);
        } catch (Exception e) {
            log.info(e.getMessage());
        }

        return ResponseEntity.ok().body(token);
    }

    @ControllerWebLog(name = "查询用户", intoDb = true)
    @PostMapping(value = "/queryUser")
    public BBM queryUserByName(@RequestBody User u) {
        return userService.queryUserByName(u.getEname());
    }
}
